var express = require("express"),
	router = express.Router(),
	getColumn = require("./public/getColumn"),
	article = require("../../models/adminSite/article"),
	articleData = "",
	articleFun = new article(),
	hotArticle = "",
	hot = function (req , res , next){
		articleFun.getArticle({conditions : {Popular : 1}} , function(error , data){
			if(error){
				return res.end("<h2>操作失败</h3>");
			};
			(hotArticle = data) && next();
		});
	};
//详情页数据获取
var getArticle = function(req , res , next){
	articleFun.getArticle({conditions : {_id : req.query.id}} , function(error , data){
		if(error){
			res.end("<h2>操作失败</h2>");
		};
		if(data){
			articleData = data[0];
			next();
		};
	});
};
//获取猜你喜欢文章
var	likeArticle = "",
	getLike = function(req , res , next){
		articleFun.getArticle({conditions : {} , limit : 6 , sort : {pubdate : -1}} , function(error , data){
			if(error){
				return res.end("<h2>操作失败</h2>");
			};
			(likeArticle = data) && next();
		})
	};
//文章列表路由
router.get("/article" , hot , function(req , res){
	articleFun.getArticle({conditions :  req.query.id && {column : req.query.id}} , function(error , article){
		if(error){
			return res.end("<h2>操作失败</h2>");
		};
		//获取栏目
		getColumn(function(column){
			res.render("webSite/article-list" , {
				title : "文章列表",
				article : article,
				hotArticle : hotArticle,
				column : column,
				columnCur : req.query.id,
				user : req.session.user,
				error : ""
			});
		});
	});
});
//ajax加载更多
router.post("/article" , function(req , res){
	articleFun.getArticle({conditions : req.query.id && {column : req.body.id} , page : req.body.page} , function(error , article){
		if(error){
			return res.json({
				state : "error",
				message : "操作失败"
			});
		};
		return res.json({
			state : "ok",
			message : "",
			data : article
		});
	});
});
//详情
router.get("/article-details" , [getArticle , getLike , hot] , function(req , res){
	getColumn(function(column){
		res.render("webSite/article-details" , {
			article : articleData,
			column : column,
			likeArticle : likeArticle,
			hotArticle : hotArticle,
			columnCur : articleData.column,
			user : req.session.user
		});
	})
});
//文章评论
router.post("/setComment" , function(req , res){
	var data = req.body,
		id = data.id;
	if(!id){
		return data.json({
			state : "error",
			message : "文章id不能为空"
		});
	};
	data = {
		content : data["data[connent]"],
		releaseTime : new Date().getTime()
	};
	articleFun.setComment(id , data , function(error , data){
		if(error){
			return res.json({
				state : "error",
				message : "评论失败"
			});
		};
		res.json({
			state : "ok",
			message : "评论成功"
		});
	});
});
//接口
module.exports = router;
